package com.jsh.erp.service.dict;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.Dict;
import com.jsh.erp.datasource.entities.Dict;
import com.jsh.erp.datasource.entities.DictExample;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.DictMapper;
import com.jsh.erp.datasource.mappers.DictMapperEx;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class DictService {
    private Logger logger = LoggerFactory.getLogger(DictService.class);

    @Resource
    private DictMapper dictMapper;
    @Resource
    private DictMapperEx dictMapperEx;

    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private DepotHeadService depotHeadService;

    public Dict getDict(long id)throws Exception {
        Dict result=null;
        try{
            result=dictMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Dict> getDictListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Dict> list = new ArrayList<>();
        try{
            DictExample example = new DictExample();
            example.createCriteria().andIdIn(idList);
            list = dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Dict> getDict()throws Exception {
        DictExample example = new DictExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Dict> list=null;
        try{
            list=dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Dict> select(String label, String type, int offset, int rows) throws Exception{
        List<Dict> resList = new ArrayList<Dict>();
        try{
            List<Dict> list = dictMapperEx.selectByConditionDict(label,type, offset, rows);
            for(Dict s : list) {
                resList.add(s);
            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return resList;
    }

    public Long countDict(String label, String type) throws Exception{
        Long result=null;
        try{
            result=dictMapperEx.countsByDict(label, type);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDict(JSONObject obj, HttpServletRequest request)throws Exception {
        Dict dict = JSONObject.parseObject(obj.toJSONString(), Dict.class);
        int result=0;
        try{
            dict.setEnabled(true);
            User userInfo=userService.getCurrentUser();
            dict.setCreator(userInfo==null?null:userInfo.getId());
            result=dictMapper.insertSelective(dict);

            logService.insertLog("字典",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(dict.getLabel()).toString(),request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDict(JSONObject obj, HttpServletRequest request)throws Exception {
        Dict contact = JSONObject.parseObject(obj.toJSONString(), Dict.class);
        int result=0;
        try{
            result=dictMapper.updateByPrimaryKeySelective(contact);
            logService.insertLog("字典",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(contact.getLabel()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDict(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteDictByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDict(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteDictByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDictByIds(String ids)throws Exception {
        int result=0;
        String [] idArray=ids.split(",");

        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Dict> list = getDictListByIds(ids);
        for(Dict project: list){
            sb.append("[").append(project.getLabel()).append("]");
        }
        logService.insertLog("字典", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        //校验通过执行删除操作
        try{
            result = dictMapperEx.batchDeleteDictByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }


    public int checkIsNameExist(Long id, String name)throws Exception {
        DictExample example = new DictExample();
        example.createCriteria().andIdNotEqualTo(id).andLabelEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Dict> list=null;
        try{
            list= dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }


    public List<Dict> findBySelect()throws Exception {
        DictExample example = new DictExample();
        example.createCriteria().andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Dict> list=null;
        try{
            list = dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Dict> findBySelectType(String type)throws Exception {
        DictExample example = new DictExample();
        example.createCriteria().andTypeLike(type).andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Dict> list=null;
        try{
            list = dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Dict> findById(Long supplierId)throws Exception {
        DictExample example = new DictExample();
        example.createCriteria().andIdEqualTo(supplierId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Dict> list=null;
        try{
            list = dictMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }


}
